package client

import (
	"context"
	"google.golang.org/grpc"
	"weekly1/user-server/protot/user"
)

type Handler func(ctx context.Context, client user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8085", grpc.WithBlock())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func UserRegister(ctx context.Context, i *user.UserRegisterReq) (*user.UserRegisterResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		register, err := client.UserRegister(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserRegisterResp), nil
}

func UserLogin(ctx context.Context, i *user.UserLoginReq) (*user.UserLoginResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		register, err := client.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResp), nil
}

func VideoAdd(ctx context.Context, i *user.VideoAddReq) (*user.VideoAddResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		add, err := client.VideoAdd(ctx, i)
		if err != nil {
			return nil, err
		}
		return add, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.VideoAddResp), nil
}
